package com.erp.programmer.controller;


import com.erp.programmer.bean.CodeMsg;
import com.erp.programmer.dao.ClientCompanyMapper;
import com.erp.programmer.dto.*;
import com.erp.programmer.service.ISaleOrderService;
import com.erp.programmer.utils.ValidateEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Takagi3
 * @since 2021-05-24
 */
@RestController
@RequestMapping("/sale_order")
@CrossOrigin
public class SaleOrderController {

    @Autowired
    private ISaleOrderService isaleOrderService;

    @Autowired
    private ClientCompanyMapper clientCompanyMapper;

    /**
     * 分页
     *新增销售订单信息
     */
    @PostMapping("/save")
    public ResponseDto<PageDto<SaleOrderDto>> saveSaleOrder(@RequestBody SaleOrderDto saleOrderDto) {
        //非空判断
        if (saleOrderDto == null) {
            return ResponseDto.errorByMsg(CodeMsg.DATA_ERROR);
        }
        //销售订单进行统一表单验证
        CodeMsg validate = ValidateEntityUtil.validate(saleOrderDto);
        if (!validate.getCode().equals(CodeMsg.SUCCESS.getCode())) {
            return ResponseDto.errorByMsg(validate);
        }
        //进行详单统一表单验证
        for (SaleOrderDetailDto saleOrderDetailDto : saleOrderDto.getSaleOrderDetailDtos()) {
            validate = ValidateEntityUtil.validate(saleOrderDetailDto);
            if (!validate.getCode().equals(CodeMsg.SUCCESS.getCode())) {
                return ResponseDto.errorByMsg(validate);
            }
        }
        //判断客户公司编号是否存在
        if(clientCompanyMapper.selectById(saleOrderDto.getClientCompanyId()) == null){
            return ResponseDto.errorByMsg(CodeMsg.CLIENT_COMPANY_NOT_EXIST);
        }
        return isaleOrderService.saveSaleOrder(saleOrderDto);
    }


    /**
     * 分页
     * 搜索获取全部销售信息
     */
    @PostMapping("/get_data")
    public ResponseDto<PageDto<SaleOrderDto>> getSaleOrder(@RequestBody PageDto<SaleOrderDto> pageDto) {
        if (pageDto==null) {
            ResponseDto.errorByMsg(CodeMsg.DATA_ERROR);
        }
        return isaleOrderService.getSaleOrders(pageDto);
    }

    /**
     * 修改支付状态
     * @param editStateDto
     * @return
     */
    @PostMapping("/edit_state")
    public ResponseDto<PageDto<SaleOrderDto>> updatePaymentState(@RequestBody EditStateDto editStateDto) {
        return isaleOrderService.updatePaymentState(editStateDto);
    }


}



